package com.tticar.invmanager.service.impl;

import com.baomidou.mybatisplus.entity.Columns;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tticar.invmanager.common.Enum.Status;
import com.tticar.invmanager.common.exception.MyServiceException;
import com.tticar.invmanager.common.utils.tree.TreeUtils;
import com.tticar.invmanager.entity.MMateriel;
import com.tticar.invmanager.entity.MMaterielSku;
import com.tticar.invmanager.entity.WPosition;
import com.tticar.invmanager.entity.WWearhouse;
import com.tticar.invmanager.entity.vo.KwTree;
import com.tticar.invmanager.entity.vo.MyPage;
import com.tticar.invmanager.entity.vo.Tree;
import com.tticar.invmanager.mapper.WWearhouseMapper;
import com.tticar.invmanager.service.*;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author joeyYan
 * @since 2018-07-02
 */
@Service
public class WWearhouseServiceImpl extends ServiceImpl<WWearhouseMapper, WWearhouse> implements IWWearhouseService {

    @Autowired
    private IWPositionService positionService;

    @Autowired
    private IMMaterielSkuService materielSkuService;

    @Autowired
    private IInRepositoryDetailService inRepositoryDetailService;

    @Override
    public Page selectPage(WWearhouse wWearhouse, MyPage<WWearhouse> page) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.orderBy("ctime", false);
        wrapper.ne(Status.STATUS.getDesc(), Status.DELETE.getCode());
        Columns columns = Columns.create().column("*")
                .column("(select case count(1) when 0 then 'open' else 'closed' end from w_wearhouse t where t.pid=w_wearhouse.id)", "state");
        wrapper.setSqlSelect(columns);
        wrapper.eq(Strings.isEmpty(wWearhouse.getName()), WWearhouse.PID, wWearhouse.getId());
        wrapper.like(Strings.isNotEmpty(wWearhouse.getName()), WWearhouse.NAME, wWearhouse.getName());
        return this.selectMapsPage(page, wrapper);
    }

    @Override
    public Page selectPageForAvailable(WWearhouse wWearhouse, MyPage<WWearhouse> page) {
        Wrapper wrapper = new EntityWrapper();
        wrapper.orderBy("ctime", false);
        wrapper.eq(Status.STATUS.getDesc(), Status.VALID.getCode());
        Columns columns = Columns.create().column("*")
                .column("(select case count(1) when 0 then 'open' else 'closed' end from w_wearhouse t where t.pid=w_wearhouse.id)", "state");
        wrapper.setSqlSelect(columns);
        wrapper.eq(Strings.isEmpty(wWearhouse.getName()), WWearhouse.PID, wWearhouse.getId());
        wrapper.like(Strings.isNotEmpty(wWearhouse.getName()), WWearhouse.NAME, wWearhouse.getName());
        return this.selectMapsPage(page, wrapper);
    }

    @Override
    public Page selectPageForSearch(WWearhouse wWearhouse, MyPage<WWearhouse> page) {
        Wrapper wrapper = new EntityWrapper();

        wrapper.ne(Status.STATUS.getDesc(), Status.DELETE.getCode());
        return this.selectMapsPage(page, wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> ids) {
        List list = new ArrayList();
        for (Long id : ids) {
            WWearhouse wWearhouse = new WWearhouse();
            wWearhouse.setId(id);
            //删除为-1，区分删除和禁用
            wWearhouse.setStatus(-1);
            list.add(wWearhouse);
            //如果有库位，则不能删除
            List<Long> longs = positionService.selectPositionIdsByWearhouseId(id);
            if (longs.size() > 0) {
                throw new MyServiceException("仓库下有库位，禁止删除");
//                List positionList = new ArrayList<>();
//                for (Long positionIds : longs) {
//                    WPosition wposiont = new WPosition();
//                    //删除为-1，区分删除和禁用
//                    wposiont.setStatus(-1);
//                    wposiont.setId(positionIds);
//                    positionList.add(wposiont);
//                }
//                positionService.updateBatchById(positionList);
            }

        }
        this.updateBatchById(list);
    }

    @Override
    public List<Tree> tree() {
        List<Tree> resultList = new ArrayList<>();
        Tree root = new Tree(0l,"全部");
        root.setPid(-1l);
        resultList.add(root);

        Wrapper wrapper = new EntityWrapper();
        wrapper.eq( WWearhouse.STATUS, 0);
        List<WWearhouse> houseList = this.selectList(wrapper);
        Long[] ids = new Long[houseList.size()];

        for(int i=0; i<houseList.size(); i++) {
            WWearhouse house = houseList.get(i);
            ids[i] = house.getId();
            Tree tree = new Tree(house.getId(), house.getName());
            tree.setState("open");
            tree.setPid(house.getPid());
            resultList.add(tree);
        }

        wrapper = new EntityWrapper();
        wrapper.eq( WWearhouse.STATUS, 0);
        List<WPosition> positionList = this.positionService.selectList(wrapper);
        for(WPosition position : positionList) {
            Tree tree = new Tree(position.getId(), position.getName());
            tree.setState("open");
            tree.setIconCls("icon-kw");
            tree.setPid(position.getWearhouseId());
            resultList.add(tree);
        }

        TreeUtils.createTree(resultList,root,"id","pid","children");

        return root.getChildren();
    }

    @Override
    public List<KwTree> treeGrid(Long skuId, Integer type, Long houseId) {
        List<KwTree> resultList = new ArrayList<>();
        KwTree root = new KwTree("0","全部");
        root.setPid("-1");
        resultList.add(root);

        Wrapper wrapper = new EntityWrapper();
        wrapper.eq(WWearhouse.STATUS, 0);
        if(houseId != null && houseId != 0) {
            wrapper.andNew().eq("id", houseId).or().eq("pid", houseId);
        }
        List<WWearhouse> houseList = this.selectList(wrapper);

        for(WWearhouse house : houseList) {
            KwTree tree = new KwTree(house.getId() + "", house.getName());
            tree.setState("open");
            tree.setPid(house.getPid() + "");
            resultList.add(tree);
        }

        MMaterielSku sku = this.materielSkuService.selectById(skuId);
        List<Map> positionList = this.positionService.getForTree(skuId, sku.getMid());
        for(Map<String, Object> position : positionList) {
            KwTree tree = new KwTree("h" + position.get("id"), (String) position.get("name"));
            tree.setNum((Long) position.get("num"));
            tree.setState("open");
            tree.setPid(position.get("pid") + "");
            resultList.add(tree);
        }

        //批次
        if(type == 0) {//出库时需要选择批次
            List<Map> batchList = this.inRepositoryDetailService.batchCodeGrid(skuId);
            for (Map<String, Object> batch : batchList) {
                KwTree tree = new KwTree("b" + batch.get("batchCode"), (String) batch.get("batchCode"));
                tree.setNum(((BigDecimal) batch.get("num")).longValue());
                tree.setState("open");
                tree.setIconCls("icon-kw");
                tree.setPid("h" + batch.get("positionId"));
                resultList.add(tree);
            }
        }

        TreeUtils.createTree(resultList,root,"id","pid","children");

        //没有库位、批次的不予显示
        List<KwTree> childList = new ArrayList<>();
        for(KwTree tree : root.getChildren()) {
            if(tree.getChildren() != null && tree.getChildren().size() > 0) {
                if(type == 0) {
                    List<KwTree> childList2 = new ArrayList<>();
                    for(KwTree tree2 : tree.getChildren()) {
                        if(tree2.getChildren() != null && tree2.getChildren().size() > 0 ) {
                            //如果批次数量为0 就不显示
                            for (int i = tree2.getChildren().size() - 1; i >= 0; i--) {
                                if (tree2.getChildren().get(i).getNum() < 1) {
                                    tree2.getChildren().remove(i);
                                }
                            }

                            childList2.add(tree2);
                        }
                    }
                    tree.setChildren(childList2);
                }
                if(tree.getChildren().size() > 0) {
                    childList.add(tree);
                }
            }
        }
        root.setChildren(childList);

        return root.getChildren();
    }

    @Override
    public List<KwTree> treeGridForBind(Long materielId) {
        List<KwTree> resultList = new ArrayList<>();
        KwTree root = new KwTree("0","全部");
        root.setPid("-1");
        resultList.add(root);

        Wrapper wrapper = new EntityWrapper();
        wrapper.eq(WWearhouse.STATUS, 0);
        List<WWearhouse> houseList = this.selectList(wrapper);

        for(WWearhouse house : houseList) {
            KwTree tree = new KwTree(house.getId() + "", house.getName());
            tree.setState("open");
            tree.setPid(house.getPid() + "");
            resultList.add(tree);
        }

        List<Map> positionList = this.positionService.getForTreeBind(materielId);
        for(Map<String, Object> position : positionList) {
            KwTree tree = new KwTree("h" + position.get("id"), (String) position.get("name"));
            tree.setState("open");
            tree.setIconCls("icon-kw");
            tree.setPid(position.get("pid") + "");
            resultList.add(tree);
        }

        TreeUtils.createTree(resultList,root,"id","pid","children");

        //没有库位不予显示
        List<KwTree> childList = new ArrayList<>();
        for(KwTree tree : root.getChildren()) {
            if(tree.getChildren() != null && tree.getChildren().size() > 0) {
                childList.add(tree);
            }
        }
        root.setChildren(childList);
        return root.getChildren();
    }
}
